package models;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.Formula;

@Entity
@Table(name="sys_zone")
@SuppressWarnings("serial")
public class Zone extends IdEntity{
	
	
	@Formula("(select COUNT(*) from sys_zone d where d.parent_id=0 or d.parent_id is NULL)")
    private int isRoot;
	
	@Formula("(select COUNT(*) from sys_zone d where d.parent_id = id)")
    private int subZoneCount;
	
	@Formula("(select COUNT(*) from sys_orgn d where d.zone_id = id)")
    private int subOrgnCount;
	
	private String name;
	private String code;
	private Integer position;
	
	@ManyToOne(fetch = FetchType.EAGER)
	private Zone parent;
	
	private Integer peopleNum;
	
	@Formula("(select SUM(z.people_num) from sys_zone z where (z.code like REPLACE(code,'000','') || '_%') OR  (z.code like REPLACE(code,'00','') || '_%'))")
	private Integer _peopleNum;
	
	public Integer getPeopleNum() {
		if(subZoneCount==0){
			return peopleNum==null?0 : peopleNum;
		}
		else{
			return _peopleNum==null?0:_peopleNum;
		}
	}
	
	public void setPeopleNum(Integer peopleNum) {
		this.peopleNum = peopleNum;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public int getIsRoot() {
		return isRoot;
	}

	public void setIsRoot(int isRoot) {
		this.isRoot = isRoot;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Zone getParent() {
		return parent;
	}

	public void setParent(Zone parent) {
		this.parent = parent;
	}

	public Integer getPosition() {
		return position;
	}

	public void setPosition(Integer position) {
		this.position = position;
	}

	public int getSubZoneCount() {
		return subZoneCount;
	}

	public void setSubZoneCount(int subZoneCount) {
		this.subZoneCount = subZoneCount;
	}

	public int getSubOrgnCount() {
		return subOrgnCount;
	}

	public void setSubOrgnCount(int subOrgnCount) {
		this.subOrgnCount = subOrgnCount;
	}

	public Integer get_peopleNum() {
		return _peopleNum;
	}

	public void set_peopleNum(Integer num) {
		_peopleNum = num;
	}

	
}
